<template>
  <div class="user-coupons">
    <el-card class="coupon-card">
      <template #header>
        <div class="card-header">
          <h3>我的优惠券</h3>
          <el-radio-group v-model="couponStatus" @change="handleStatusChange">
            <el-radio-button value="valid">未使用</el-radio-button>
            <el-radio-button value="used">已使用</el-radio-button>
            <el-radio-button value="expired">已过期</el-radio-button>
          </el-radio-group>
        </div>
      </template>

      <div class="coupon-list" v-loading="loading">
        <el-empty v-if="!couponList.length" :description="getEmptyText()" />
        
        <div v-else class="coupon-grid">
          <div 
            v-for="coupon in couponList" 
            :key="coupon.id" 
            class="coupon-item"
            :class="{ 'is-disabled': coupon.status !== 0 }"
          >
            <div class="coupon-left">
              <div class="amount">
                <span class="currency">¥</span>
                <span class="number">{{ coupon.couponData.value }}</span>
              </div>
              <div class="condition">
                <template v-if="coupon.couponData.type === 1">
                  满{{ coupon.couponData.minAmount }}可用
                </template>
                <template v-else-if="coupon.couponData.type === 2">
                  无门槛秒杀券
                </template>
              </div>
            </div>
            <div class="coupon-right">
              <h4 class="title">{{ coupon.couponData.name }}</h4>
              <p class="desc">优惠券码：{{ coupon.couponCode }}</p>
              <div class="date-range">
                领取时间：{{ formatDate(coupon.obtainTime) }}
              </div>
              <div class="date-range" v-if="coupon.usedTime">
                使用时间：{{ formatDate(coupon.usedTime) }}
              </div>
              <div class="date-range">
                过期时间：{{ formatDate(coupon.expireTime) }}
              </div>
              <div class="status-tag">
                <el-tag 
                  :type="getStatusType(coupon.status)"
                  size="small"
                >
                  {{ getStatusText(coupon.status) }}
                </el-tag>
                <el-tag 
                  v-if="coupon.couponData.stackable"
                  type="success" 
                  size="small"
                  style="margin-left: 5px;"
                >
                  可叠加
                </el-tag>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 分页 -->
      <div class="pagination-container" v-if="total > 0">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { getCouponList as fetchCouponList } from '@/api/coupon'

// 状态数据
const loading = ref(false)
const couponStatus = ref('valid')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const couponList = ref([])

// 状态映射
const STATUS_MAP = {
  valid: 0,    // 未使用
  used: 1,     // 已使用
  expired: 2   // 已过期
}

// 获取优惠券列表
const getCouponList = async () => {
  loading.value = true
  try {
    const res = await fetchCouponList({
      status: STATUS_MAP[couponStatus.value],
      page: currentPage.value,
      pageSize: pageSize.value
    })
    
    couponList.value = res.records || []
    total.value = res.total || 0
  } catch (error) {
    console.error('获取优惠券列表失败：', error)
    ElMessage.error(error.message || '获取优惠券列表失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return ''
  return new Date(date).toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 获取状态类型
const getStatusType = (status) => {
  const typeMap = {
    0: 'success',  // 未使用
    1: 'info',     // 已使用
    2: 'danger'    // 已过期
  }
  return typeMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const textMap = {
    0: '未使用',
    1: '已使用',
    2: '已过期'
  }
  return textMap[status] || '未知状态'
}

// 获取空状态文本
const getEmptyText = () => {
  const textMap = {
    valid: '暂无可用优惠券',
    used: '暂无已使用优惠券',
    expired: '暂无已过期优惠券'
  }
  return textMap[couponStatus.value] || '暂无优惠券'
}

// 状态切换
const handleStatusChange = () => {
  currentPage.value = 1
  getCouponList()
}

// 分页相关方法
const handleSizeChange = (val) => {
  pageSize.value = val
  getCouponList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  getCouponList()
}

// 获取优惠券类型文本
const getCouponTypeText = (type) => {
  const typeMap = {
    1: '满减券',
    2: '无门槛秒杀券'
  }
  return typeMap[type] || '未知类型'
}

// 初始化
onMounted(() => {
  getCouponList()
})
</script>

<style scoped>
.user-coupons {
  width: 100%;
}

.coupon-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
}

.coupon-grid {
  display: grid;
  gap: 20px;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
}

.coupon-item {
  display: flex;
  background: linear-gradient(135deg, var(--el-color-primary-light-9) 0%, var(--el-color-primary-light-7) 100%);
  border-radius: 8px;
  overflow: hidden;
  transition: all 0.3s;
}

.coupon-item:hover {
  transform: translateY(-5px);
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.coupon-item.is-disabled {
  opacity: 0.6;
  background: linear-gradient(135deg, #f5f5f5 0%, #e0e0e0 100%);
}

.coupon-left {
  width: 120px;
  padding: 20px;
  background: var(--el-color-primary);
  color: white;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  position: relative;
}

.amount {
  font-size: 32px;
  font-weight: bold;
}

.currency {
  font-size: 16px;
  margin-right: 2px;
}

.condition {
  font-size: 12px;
  margin-top: 5px;
  text-align: center;
  line-height: 1.4;
}

.coupon-right {
  flex: 1;
  padding: 15px;
  position: relative;
}

.title {
  margin: 0 0 10px;
  font-size: 16px;
  font-weight: bold;
}

.desc {
  margin: 0 0 10px;
  font-size: 12px;
  color: var(--el-text-color-secondary);
}

.date-range {
  font-size: 12px;
  color: var(--el-text-color-secondary);
}

.status-tag {
  position: absolute;
  top: 15px;
  right: 15px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>